/*
Program to export matrices to CSV
*/

cap program drop exportmat
program define exportmat
  * first arg: matrix to export
  * second arg: filename it will become
  * third arg: directory to save it in
  syntax anything, filename(string) path(string) export(integer)
  preserve
  qui: mat define tempmat = `anything'
  clear
  qui: svmat tempmat
  qui: gen id = _n 
  qui: reshape long tempmat, i(id) j(X_id)
  qui: reshape wide tempmat, i(X_id) j(id)
  local RN : rownames tempmat
  ren (tempmat*) (`RN')
  local CN : colnames tempmat
  local CN : subinstr local CN "." "_", all
  local CN : subinstr local CN "#" "_", all
  local CN : subinstr local CN ":" "_", all
  local i = 0
  qui: gen X = ""
  foreach var in `CN' {
      local i = `i' + 1
      qui: replace X = "`var'" if _n == `i'
  }
  
  ** export via fpost
  local cwd `c(pwd)'
  cd `path'
  export delimited using `filename', replace  
  if (`export' != 0) {
      ! /ssb/bruker/nbn/fpost `filename'
  }
  cd "`cwd'"
  restore
end
